package com.example.zbh.dsliao.ui.activty;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.zbh.dsliao.MusicIdle;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.model.entity.NetSongList;
import com.example.zbh.dsliao.presenter.SongListPresenter;
import com.example.zbh.dsliao.ui.adapter.LocalMusicListViewAdapter;
import com.example.zbh.dsliao.ui.adapter.SongListAdapter;
import com.example.zbh.dsliao.ui.viewinterface.ShowDownLoaderResultListener;
import com.example.zbh.dsliao.utils.FormatTime;
import com.example.zbh.dsliao.utils.FullyGridLayoutManager;
import com.example.zbh.dsliao.utils.MyEventBus;
import com.example.zbh.dsliao.utils.net.VolleySingleton;
import com.example.zbh.dsliao.view.CustomDialog;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * Created by yaolin on 15/11/23.
 */
public class SongListActivity extends MVPBaseActivity<ShowDownLoaderResultListener, SongListPresenter> implements SongListAdapter.setOnclickListener, View.OnClickListener, SeekBar.OnSeekBarChangeListener, SongListAdapter.OnDownLoaderClickListener, ShowDownLoaderResultListener {
    private ImageView img_play, img_previous, img_next, img_order, img_radom, img_single, img_back;
    private TextView song, maxTv, progressTv;
    private SeekBar progress;
    private RelativeLayout title_layout;
    private RecyclerView listView;
    private SongListAdapter adapter;
    private int currentIndex;
    private List<NetSongList> list;
    private NextBroadcastReceiver nextBroadcastReceiver;
    private Intent intent;

    private final static String mode_random = "RADOM_MODE"; //随机播放
    private final static String mode_order = "ORDER_MODE"; //循环播放
    private final static String mode_single = "SINGLE_MODE"; //单曲循环
    private int random;


    private CustomDialog customDialog;

    //网络请求
    VolleySingleton volleySingleton = VolleySingleton.getInstance();

    //定义一个播放的接口操作对象
    private MusicIdle musicIdle;
    //定义一个远程服务连接对象
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //初始化操作对象
            musicIdle = MusicIdle.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };




    @Override
    protected int getLayOut() {
        return R.layout.activity_song_list;
    }

    @Override
    protected void initView() {
        img_back = findeView(R.id.img_back);
        img_back.setOnClickListener(this);

        img_play = findeView(R.id.img_play);                    //播放按钮
        img_play.setOnClickListener(this);

        img_previous = findeView(R.id.img_previous);            //上一首
        img_previous.setOnClickListener(this);

        img_next = findeView(R.id.img_next);                    //下一首
        img_next.setOnClickListener(this);

        song = findeView(R.id.song);                           //歌名 + 歌手
        maxTv= findeView(R.id.tv_time_max);                    //歌曲时长
        progressTv = findeView(R.id.tv_time_progress);         //当前时长

        progress = findeView(R.id.progress);                   //拖动条
        progress.setOnSeekBarChangeListener(this);


        img_order = (ImageView) findViewById(R.id.img_order);   //循环播放
        img_order.setOnClickListener(this);

        img_radom = (ImageView) findViewById(R.id.img_radom);   //随机播放
        img_radom.setOnClickListener(this);

        img_single = (ImageView) findViewById(R.id.img_single); //单曲播放
        img_single.setOnClickListener(this);


        listView = findeView(R.id.listView);
        FullyGridLayoutManager gm = new FullyGridLayoutManager(this, 1);
        listView.setLayoutManager(gm);

        adapter = new SongListAdapter(this);
        listView.setAdapter(adapter);

        adapter.setListener(this);
        adapter.setOnDownLoaderClickListener(this);

    }



    @Override
    protected void initData() {
        //初始化dialog
        customDialog = new CustomDialog(this, "玩命加载中...");
        //注册EventBus
        EventBus.getDefault().register(this);
        //网络请求
//        requestContent();
        createPresenter().startSongListConnection(getUrl());


        //绑定远程服务  还需要解绑  要不退出时报异常
        intent = new Intent("com.lanou.service.player");
        bindService(intent, conn, BIND_AUTO_CREATE);
        //注册自定义动态广播消息
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.lanou.player.next");
        filter.addAction("com.lanou.player.previous");
        filter.addAction("com.lanou.player.radomPlay");
        filter.addAction("com.lanou.player.singlelay");
        nextBroadcastReceiver = new NextBroadcastReceiver();
        //动态注册广播接收器,注册的广播接收器相当于一个匿名类
        registerReceiver(nextBroadcastReceiver, filter);
    }

    @Override
    protected SongListPresenter createPresenter() {
        return new SongListPresenter(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //取消注册接收器
        unregisterReceiver(nextBroadcastReceiver);
        //解绑服务
        unbindService(conn);
        //取消注册
        EventBus.getDefault().unregister(this);

        if (adapter != null) {
            adapter.unRegister();
        }
    }


    //当前进度
    public void onEvent(MyEventBus.CurrentIndex currentIndex) {
        Log.d("SongListActivity", "currentIndex:" + currentIndex);
        progress.setProgress(currentIndex.getCurrentIndex());
        progressTv.setText(FormatTime.formatTime((long) currentIndex.getCurrentIndex()));
    }

    //最大进度
    public void onEvent(MyEventBus.MaxProgress maxProgress) {
        Log.d("SongListActivity", "maxProgress:" + maxProgress);
        progress.setMax(maxProgress.getMaxProgress());
        maxTv.setText(FormatTime.formatTime((long) maxProgress.getMaxProgress()));
    }


    //随机播放---随机数
    public void onEvent(MyEventBus.RandomMode randomMode){
        this.random = randomMode.getPlayerRandom();
        Log.i("lanou3g", "随机播放产生的随机数是:" + this.random);
    }

    public String getUrl(){
        return "http://api.dongting.com/frontpage/module/songlist?address=%E8%BE%BD%E5%AE%81%E7%9C%81%E5%A4%A7%" +
                "E8%BF%9E%E5%B8%82%E6%B2%99%E6%B2%B3%E5%8F%A3%E5%8C%BA%E4%BA%94%E4%B8%80%E8%B7%AF314&deviceId=868047020810943&s=s200&agent=none&moduleId=2794&" +
                "longitude=121.54458&userId=0&utdid=VMHiWuA6%2FAoDAAlPEVZoReUw&net=2&from=android&rom=Meizu%252Fmeizu_" +
                "m2%252Fm2%253A5.1%252FLMY47D%252F1442477531%253Auser%252Frelease-keys&os=5.1&v=v8.3.0.2015110214&alf=702008&api_version=1.0&" +
                "imei=868047020810943&latitude=38.883507&f=62&resolution=720x1280&language=zh&user_id=0";
    }

    /**
     * 列表的行监听事件
     **/
    @Override
    public void onItemClick(NetSongList data, int position) {
        try {
            if (musicIdle != null) {
                musicIdle.setUrl(data.getAuditionList().get(0).getUrl());
                img_play.setImageResource(R.mipmap.deep_pause_btn);
                song.setText(data.getName() + "         " + data.getSingerName());
                currentIndex = position;  //当前位置



            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }

        //EventBus练习
        List<String> strings = new ArrayList<>();
        strings.add("lallalala");
        EventBus.getDefault().post(new MyEventBus.TestClass(strings));
    }



    /**
     * seekBar的监听事件
     * **/
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if(musicIdle != null){
            try {
                musicIdle.setProgress(seekBar.getProgress());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }


    //下载歌曲接口 执行传值跳转工作
    @Override
    public void OnDownLoaderClick(NetSongList songList) {
        Intent intent = new Intent();
        intent.setClass(this, DownLoaderActivity.class);
        intent.putExtra("song", songList);
        startActivity(intent);
    }

    @Override
    public void showResult(List list) {
        this.list = list;
        adapter.addData(list);
    }

    @Override
    public void showOtherResult(List list) {

    }

    /**
     * 自定义动态广播
     **/
    public class NextBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals("com.lanou.player.next")) {
                if (musicIdle != null) {
                    currentIndex++;
                    Log.i("lanou3g", "循环模式:" + currentIndex);
                }
            } else if (intent.getAction().equals("com.lanou.player.previous")) {
                if (musicIdle != null) {
                    currentIndex--;
                    Log.i("lanou3g", "上一首:" + currentIndex);
                }
            } else if (intent.getAction().equals("com.lanou.player.radomPlay")) {
                if (musicIdle != null) {
                    currentIndex = random;
                    Log.i("lanou3g", "随机模式:" + currentIndex);
                }
            } else if (intent.getAction().equals("com.lanou.player.singlelay")) {
                if (musicIdle != null) {
                    currentIndex = currentIndex;
                    Log.i("lanou3g", "单曲循环:" + currentIndex);
                }
            }

            img_play.setImageResource(R.mipmap.deep_pause_btn);
            song.setText(list.get(currentIndex % list.size()).getName() + "         " + list.get(currentIndex % list.size()).getSingerName());

            Log.i("lanou3g", "广播" + list.get(currentIndex % list.size()).getName() + "--->" +
                    list.get(currentIndex % list.size()).getSingerName());
            String url = list.get(currentIndex % list.size()).getAuditionList().get(0).getUrl();

            //发送当前播放的位置
            EventBus.getDefault().post(new MyEventBus.PlayerCurrentIndex(currentIndex));

            try {
                musicIdle.setUrl(url);
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 监听事件
     **/
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.img_play:  //暂停
                pause();
                break;

            case R.id.img_previous:   //上一首
                next();
                break;

            case R.id.img_next:  //下一首
                previous();
                break;

            case R.id.img_order:  //随机播放
                order();
                break;
            case R.id.img_radom:  //单曲播放
                radom();
                break;

            case R.id.img_single:   //循环播放
                single();
                break;
        }
    }

    /**单曲循环**/
    private void single() {
        img_order.setVisibility(View.VISIBLE);
        img_radom.setVisibility(View.GONE);
        img_single.setVisibility(View.GONE);
        Toast.makeText(this, "循环播放", Toast.LENGTH_SHORT).show();
        EventBus.getDefault().post(new MyEventBus.PlayerMode(mode_order));
    }

    /**随机播放**/
    private void radom() {
        img_order.setVisibility(View.GONE);
        img_radom.setVisibility(View.GONE);
        img_single.setVisibility(View.VISIBLE);
        Toast.makeText(this, "单曲播放", Toast.LENGTH_SHORT).show();
        EventBus.getDefault().post(new MyEventBus.PlayerMode(mode_single));
    }

    /**顺序播放**/
    private void order() {
        img_order.setVisibility(View.GONE);
        img_radom.setVisibility(View.VISIBLE);
        img_single.setVisibility(View.GONE);
        EventBus.getDefault().post(new MyEventBus.PlayerMode(mode_random));
        Toast.makeText(this, "随机播放", Toast.LENGTH_SHORT).show();
    }

    /**上一首**/
    private void previous() {
        if (musicIdle != null) {
            try {
                musicIdle.next();
                song.setText(list.get(currentIndex % list.size()).getName() + "   "
                        + list.get(currentIndex % list.size()).getSingerName());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    /**下一首**/
    private void next() {
        if (musicIdle != null) {
            try {
                musicIdle.previous();
                song.setText(list.get(currentIndex % list.size()).getName() + "   "
                        + list.get(currentIndex % list.size()).getSingerName());
                Log.i("lanou3g", "--->>" + musicIdle.getDuration());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void pause() {
        if (musicIdle != null) {
            try {
                musicIdle.pause();
                img_play.setImageResource(R.mipmap.deep_play_btn);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
}
